package com.crack.nga2.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.crack.nga2.R;
import com.crack.nga2.activity.FloorActivity;
import com.crack.nga2.activity.NgaApplication;
import com.crack.nga2.custom.PullListView;
import com.crack.nga2.entity.Floor;
import com.crack.nga2.entity.Medal;
import com.crack.nga2.entity.User;
import com.crack.nga2.entity.data.FloorData;
import com.crack.nga2.span.ClickableMovementMethod;
import com.crack.nga2.span.ImageSpanWrapper;
import com.crack.nga2.span.SpanUtil;
import com.crack.nga2.utils.GlobalConst;
import com.crack.nga2.utils.TimeUtils;
import com.crack.nga2.volley.PhotoUrlRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 呈现楼层数据的Fragment
 * Created by Administrator on 2015/12/17.
 */
public class FloorFragment extends Fragment implements PullListView.OnRefreshListener {
    /**
     * rootView
     */
    private PullListView rootView;
    /**
     * 楼层内容
     */
    private List<Floor> floors = new ArrayList<>();
    /**
     * adapter
     */
    private FloorAdapter adapter = new FloorAdapter();
    /**
     * 主题帖标题
     */
    private String theme_title;
    /**
     * 用户
     */
    private Map<Integer, User> users;
    /**
     * true:已经被设置过数据
     * false:还没有数据
     */
    private boolean flag;
    private Map<Integer, Medal> medals;
    private int page;

    public void setPage(int page) {
        this.page = page;
    }

    public boolean getFlag() {
        return flag;
    }

    public void setData(FloorData data) {
        flag = true;
        theme_title = data.getTheme().getSubject();
        users = data.users;
        medals = data.medals;
        floors.clear();
        floors.addAll(data.getFloors());
        adapter.notifyDataSetChanged();
        if (rootView != null) {
            rootView.onCompleteRefresh();
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = (PullListView) inflater.inflate(R.layout.fragment_floor, container, false);
        rootView.setAdapter(adapter);
        rootView.onCompleteRefresh();
        if (!flag) {
            rootView.onStartHeadRefresh();
        }
        rootView.setOnRefreshListener(this);
        return rootView;
    }

    @Override
    public void pullDownToRefresh() {
        FloorActivity activity = (FloorActivity) getActivity();
        activity.getData(page);
    }

    @Override
    public void pullUpToRefresh() {
        FloorActivity activity = (FloorActivity) getActivity();
        activity.nextPage();
        rootView.onCompleteRefresh();
    }


    private class FloorAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return floors.size();
        }

        @Override
        public Object getItem(int position) {
            return floors.get(position);
        }

        @Override
        public long getItemId(int position) {
            return floors.get(position).getPid();
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            Floor floor = floors.get(position);
//            UserInfo info = floor.getUserInfo();
            final ViewHolder holder;
            if (view == null) {
                view = View.inflate(getContext(), R.layout.activity_floor_item, null);
                holder = new ViewHolder();
                holder.post_title = (TextView) view.findViewById(R.id.post_title);
                holder.tv_user_name = (TextView) view.findViewById(R.id.tv_user_name);
                holder.tv_floor_index = (TextView) view.findViewById(R.id.tv_floor_index);
                holder.tv_user_id = (TextView) view.findViewById(R.id.tv_user_uid);
                holder.tv_user_level = (TextView) view.findViewById(R.id.tv_user_level_value);
                holder.tv_reputation = (TextView) view.findViewById(R.id.tv_user_reputation_value);
                holder.tv_user_post = (TextView) view.findViewById(R.id.tv_user_post_count);
                holder.tv_quote = (TextView) view.findViewById(R.id.tv_quote);
                holder.tv_reply_content = (TextView) view.findViewById(R.id.tv_content);
                holder.tv_reply_time = (TextView) view.findViewById(R.id.tv_reply_time);
                holder.iv_gift = (ImageView) view.findViewById(R.id.iv_gift);
                holder.iv_quote = (ImageView) view.findViewById(R.id.iv_quote);
                holder.iv_more = (ImageView) view.findViewById(R.id.iv_more);
                holder.tv_phone = (TextView) view.findViewById(R.id.tv_phone);
                holder.iv_photo = (ImageView) view.findViewById(R.id.iv_photo);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            if (position == 0) {
                holder.post_title.setVisibility(View.VISIBLE);
                holder.post_title.setText(theme_title);
            } else {
                holder.post_title.setVisibility(View.GONE);
            }
            if (floor.getLou() == 0) {
                holder.tv_floor_index.setText("楼主");
            } else {
                holder.tv_floor_index.setText(floor.getLou() + "楼");
            }
            int authorId = floor.getAuthorid();
            final User user;
            if (authorId != -1) {
                user = users.get(floor.getAuthorid());
            } else {
                user = getAnonymousUser();
            }
            holder.tv_user_id.setText(String.valueOf(floor.getAuthorid()));
            //用户名字
            if (user != null) {
                String username = user.getUsername();
                holder.tv_user_name.setText(username);
                holder.tv_user_name.setTag(user.getUid());
                //声望
                holder.tv_reputation.setText(String.valueOf(user.getF_reputation() / 10));
                //查询是否有自定义声望名称
                holder.tv_user_level.setText(user.getF_level());
                holder.tv_user_post.setText(String.valueOf(user.getPostnum()));
            }
            String content = floor.getContent();
            holder.tv_quote.setVisibility(View.GONE);

            SpannableStringBuilder quote = floor.getQuote();
            if (!TextUtils.isEmpty(quote)) {
                holder.tv_quote.setVisibility(View.VISIBLE);
                holder.tv_quote.setTag(floor.getLou());
                holder.tv_quote.setText(quote);
                loadImage(holder.tv_quote, quote);
                holder.tv_quote.setMovementMethod(ClickableMovementMethod.getInstance());
            }

            if (content != null) {
                holder.tv_reply_content.setTag(floor.getLou());
                holder.iv_gift.setTag(floor.getPid());
                SpannableStringBuilder sp = floor.getSp();
                SpanUtil.collapseSpan(sp, holder.tv_reply_content);
                holder.tv_reply_content.setText(sp);
                loadImage(holder.tv_reply_content, sp);
                holder.tv_reply_content.setMovementMethod(ClickableMovementMethod.getInstance());
            } else if (floor.getSubject() != null) {
                holder.tv_reply_content.setText(floor.getSubject());
            }
            holder.iv_quote.setTag(floor.getPid());
            holder.iv_more.setTag(floor.getPid());
            holder.tv_phone.setText(floor.getClient());
            holder.tv_reply_time.setText(TimeUtils.format(floor.getPostdatetimestamp() * 1000));
            //背景颜色交替显示
            if (floor.getLou() % 2 == 0) {
                view.setBackgroundColor(getResources().getColor(R.color.floor_item_body_2));
            } else {
                view.setBackgroundColor(getResources().getColor(R.color.floor_item_body_1));
            }
            //设置头像
            holder.iv_photo.setImageResource(R.drawable.default_icon);
            if ((GlobalConst.WIFI_AVAILABLE || GlobalConst.settings.get("2G/3G/4G网络下载头像")) && user != null) {
                final int uid = user.getUid();
                holder.iv_photo.setTag(uid);
                String photoUrl = user.getPhotoUrl();
                if (photoUrl != null) {
                    loadPhoto(holder.iv_photo, photoUrl, user.getUid());
                } else if (user.getUid() != -1) {
                    String url = "http://bbs.ngacn.cc/nuke.php?__act=get_avatar&__lib=ucp&uid=" + user.getUid() + "&__nodb&lite=js";
                    RequestQueue queue = NgaApplication.getQueue();
                    queue.add(new PhotoUrlRequest(Request.Method.GET, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            user.setPhotoUrl(response);
                            loadPhoto(holder.iv_photo, response, uid);
                        }
                    }));
                }
            }
            return view;
        }

        /**
         * 返回一个匿名用户
         */
        private User getAnonymousUser() {
            User user = new User();
            user.setF_level("学徒");
            user.setF_reputation(0);
            user.setPostnum(0);
            user.setUsername("#匿名用户#");
            return user;
        }

        private void loadImage(TextView textView, SpannableStringBuilder sp) {
            if (GlobalConst.WIFI_AVAILABLE || GlobalConst.settings.get("2G/3G/4G网络下载图片")) {
                ImageSpanWrapper wrapper = new ImageSpanWrapper(textView);
                textView.setTag(R.id.action_post, wrapper);
                wrapper.loadImage(0, sp.length());
            }
        }

        private void loadPhoto(final ImageView iv_photo, final String response, final int uid) {
            ImageLoader imageLoader = NgaApplication.getImageLoader();
            ImageLoader.ImageContainer container = imageLoader.get(response, new ImageLoader.ImageListener() {
                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                    Bitmap bitmap = response.getBitmap();
                    if (bitmap != null && iv_photo.getTag() != null && iv_photo.getTag().equals(uid)) {
                        iv_photo.setImageBitmap(bitmap);
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }, 80, 80);
            if (container != null && iv_photo.getTag() != null && iv_photo.getTag().equals(uid)) {
                Bitmap bitmap = container.getBitmap();
                if (bitmap != null) {
                    iv_photo.setImageBitmap(bitmap);
                }
            }
        }

    }


    private class ViewHolder {
        TextView post_title;
        ImageView iv_photo;
        TextView tv_floor_index;
        TextView tv_user_name;
        TextView tv_user_id;
        TextView tv_user_level;
        TextView tv_reputation;
        TextView tv_user_post;
        TextView tv_quote;
        TextView tv_reply_content;
        TextView tv_reply_time;
        ImageView iv_gift;
        ImageView iv_quote;
        ImageView iv_more;
        TextView tv_phone;
    }
}
